<?php
require_once 'Zend/Controller/Plugin/Abstract.php';

class My_Controller_Plugin_Init extends Zend_Controller_Plugin_Abstract
{
    protected $_env;
    protected $_front;
    protected $_registry;
    protected $_config;
    
    public function __construct($env = 'production')
    {
        $this->_env = $env;
        
        $this->_registry = new Zend_Registry(array(), ArrayObject::ARRAY_AS_PROPS);
        Zend_Registry::setInstance($this->_registry);
        
        $this->_disableMagicQuotes();
        
        $this->_initEnv()
             ->_initConfig()
             ->_initCache()
             ->_initSession()
             ->_initLogger()
             ->_initDb()
             ->_initFrontController()
             ->_initRouter()
             ->_initErrorHandler()
             ->_initLocale()
             ->_initModel()
             ->_initAuth()
             ->_initAcl()
             ->_initView();
    }

    protected function _initEnv()
    {
        error_reporting(E_ALL | E_STRICT);
        ini_set('display_errors', true);
        date_default_timezone_set('Asia/Singapore');
        
        Zend_Registry::set('envStage', $this->_env);
        
        return $this;
    }

    protected function _initConfig()
    {
        $config = new Zend_Config_Ini(APPLICATION_PATH . '/config/config.ini', $this->_env);
        
        $this->_config = $this->_registry->config = $config;
        
        return $this;
    }
    
    protected function _initSession()
    {
        Zend_Session::setOptions($this->_config->session->toArray());  

        $session = new Zend_Session_Namespace('APPLICATION_SESSION');
        Zend_Registry::set('session', $session);
        
        return $this;
    }
   
    protected function _initLogger()
    {
    	$config = $this->_config->log;
    	
    	if($config->enabled)
    	{
        	$writer = new Zend_Log_Writer_Firebug();
        	$writer->setPriorityStyle(8, 'TABLE');
    	}
        else
        {
        	$writer = new Zend_Log_Writer_Null();
        }
        	
        	
        $logger = new Zend_Log($writer);
        $logger->addPriority('TABLE', 8);
        
        $this->_registry->logger = $logger;
        
        return $this;
    }

    protected function _initCache()
    {
        $config = $this->_config->cache;
        $frontendOptions = (!empty($config->frontendOptions)) ? $config->frontendOptions->toArray() : array();
        $backendOptions = (!empty($config->backendOptions)) ? $config->backendOptions->toArray() : array();
        
        $cache = Zend_Cache::factory($config->frontendName, 
                                     $config->backendName, 
                                     $frontendOptions, 
                                     $backendOptions);
                                     
        $this->_registry->cache = $cache;
        
        if ($config->enablePluginLoaderCache) {
            $classFileIncCache = APPLICATION_PATH . '/data/cache/pluginLoaderCache.php';
            
            if (file_exists($classFileIncCache)) {
                require_once $classFileIncCache;
            }
            
            Zend_Loader_PluginLoader::setIncludeFileCache($classFileIncCache);
        }
        

        return $this;
    }


    protected function _initFrontController()
    {
        $this->_front = Zend_Controller_Front::getInstance();
        
        $this->_front->throwExceptions(false)
                     ->addModuleDirectory(APPLICATION_PATH . '/modules')
                     ->setParam('noErrorHandler', true);
        
        Zend_Controller_Action_HelperBroker::addPrefix('My_Controller_Action_Helper');
        
        return $this;
    }
    
    protected function _initRouter()
    {
        $router = $this->_front->getRouter();
        
        $imageThumbnailRoute = new Zend_Controller_Router_Route_Regex(
		    'images/(\d+)x(\d+)/(scale|smart|force)/(\d+)/(\d+)/(.*?)',
		    array(
		    	'module' => 'default',
		        'controller' => 'image',
		        'action'     => 'thumbnail'
		    ),
		    array(
		    	'1' => 'width',
		    	'2' => 'height',
		    	'3' => 'type',
		    	'4' => 'quality',
		    	'5' => 'id',
		    	'6' => 'name'
		    )
		);

        $router->addRoute('images', $imageThumbnailRoute);
        
        return $this;
        
    }
    
    protected function _initErrorHandler()
    {
        $this->_front->registerPlugin(new My_Controller_Plugin_ErrorHandler(), 1);
        
        return $this;
    }
        
    protected function _initLocale()
    {
        $this->_front->registerPlugin(new My_Controller_Plugin_Locale, 2);
        
        return $this;
    }
    
    protected function _initModel()
    {
        $this->_front->registerPlugin(new My_Controller_Plugin_Model, 3);
        
        return $this;
    }
    
    protected function _initAuth()
    {
        $this->_front->registerPlugin(new My_Controller_Plugin_Auth, 4);
        
        return $this;
    }

    protected function _initAcl()
    {    
        $aclPluginOptions = array();
       
        $this->_front->registerPlugin(new My_Controller_Plugin_Acl($aclPluginOptions), 5);
        
        Zend_Controller_Action_HelperBroker::addHelper(new My_Controller_Action_Helper_Acl);
        
        return $this;
    }
 

    protected function _initDb()
    {
        $config = $this->_config->doctrine;
        
        $manager = Doctrine_Manager::getInstance();
       // $manager->setAttribute('use_dql_callbacks', true);
        $manager->setAttribute(Doctrine::ATTR_QUOTE_IDENTIFIER, true);
        
        foreach($config->connection as $connSetting)
        {
            if($connSetting->is_active)
            {
                $conn = Doctrine_Manager::connection($connSetting->dsn, $connSetting->name);
                $conn->setCharset('utf8');
                
                if($connSetting->use_profiler)
                {
                    $this->_registry->doctrineProfiler = $profiler = new Doctrine_Connection_Profiler();
    
                    $conn->setListener($profiler);    
                }
                
                if($connSetting->cache->is_enabled)
                {
                    switch($connSetting->cache->driver)
                    {
                        case 'Apc':
                            $cacheDriver = new Doctrine_Cache_Apc();
                            break;
                            
                        case 'Memcache':
                            $cacheServers = $connSetting->cache->servers->toArray();
                            $cacheDriver = new Doctrine_Cache_Memcache($cacheServers);
                            break;
                            
                        case 'Db':
                            $dbCacheConn  = Doctrine_Manager::connection($connSetting->cache->options->dsn, 'cache');
                            $cacheDriver = new Doctrine_Cache_Db(array('connection' => $dbCacheConn, 
                            										   'tableName'  => $connSetting->cache->options->table_name));
                            
                            break;
                            
                        default:
                            throw new Exception("Unknown cache driver ".$connSetting->cache->driver);
                    }
                    
                    $conn->setAttribute(Doctrine::ATTR_CACHE, $cacheDriver);
                    $conn->setAttribute(Doctrine::ATTR_QUERY_CACHE, $cacheDriver);
                    $conn->setAttribute(Doctrine::ATTR_RESULT_CACHE, $cacheDriver);
                }
                
            }
        }
        
        foreach($config->connection as $connSetting)
        {
            if($connSetting->is_default)
            {
                Doctrine_Manager::getInstance()->setCurrentConnection($connSetting->name);
                break;
            }
        }
        
        return $this;
    }

    protected function _initView()
    {
        Zend_Layout::startMvc();
        $this->_front->registerPlugin(new My_Controller_Plugin_View, 6);
        
        return $this;
    }
    
	protected function _disableMagicQuotes()
    {
        if (get_magic_quotes_gpc()) {
            $_GET = self::stripSlashes($_GET);
            $_POST = self::stripSlashes($_POST);
            $_REQUEST = self::stripSlashes($_REQUEST);
            $_COOKIE = self::stripSlashes($_COOKIE);
        }
    }
    
	public static function stripSlashes($value)
    {
        if (is_array($value)) {
            $value = array_map(array(self, 'stripSlashes'), $value);
        } else {
            $value = stripslashes($value);
        }
        return $value;
    }

}